﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using L.Basic.Authority.Context;
using L.Basic.Authority.Models;

using L.Basic.Cache;
using L.Basic.Authority.Services;

namespace L.Manage
{
    public class Authentication
    {
        #region 常量
        private static object locker = new object();
        private const string UserContext = "_UserContext_";
        #endregion

        #region 用户认证上下文
        public static Context Context
        {
            get
            {
                var cache = IocFactory.Resolve<ICache>();
                var context = cache.GetSessionCache<Context>(UserContext);
                return context;
            }
             set
            {
                var cache = IocFactory.Resolve<ICache>();

                cache.SetSessionCache(UserContext, value);
            }
        }



        #endregion 用户认证上下文


        public static bool IsAuthenticated
        {
            get
            {
                if (Context != null)
                    return true;
                return false;
            }
        }

        #region 用户认证操作

        #region 实例化用户认证服务

        private static IAuthenticationService _authenticationService;

        public static IAuthenticationService AuthenticationService
        {
            get
            {
                if (_authenticationService == null)
                    lock (locker)
                    {
                        if (null == _authenticationService)
                        {
                            _authenticationService = IocFactory.Resolve<IAuthenticationService>();
                        }
                    }
                return _authenticationService;
            }

        }
        #endregion 用户认证操作

        public static UserLogin GetLoginInfo(string userId)
        {
            return AuthenticationService.GetLoginInfo(userId);
        }

        public static void SetLoginInfo(string userId, string loginIp, DateTime loginDate)
        {
            AuthenticationService.UpdateLoginInfo(userId, loginIp, loginDate);
        }

        public static bool Login(string loginName, string password)
        {
            Context context;
            if (AuthenticationService.Login(loginName, password,out context))
            {
                Context = context;
                return true;
            }
            return false;
        }

        public static void Logout()
        {
            Context = null;
        }

        public static bool ChangePassword(string loginName, string oldPassword, string newPassword)
        {
            return AuthenticationService.ChangePassword(loginName, oldPassword, newPassword);
        }


        #endregion
    }
}
